import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components';
import { request_good } from '../../untils/request';
import { ajax } from '../../untils/syncajax'
import configs from '../../configuration/index'
import './index.scss';
import { set as setGlobalData } from '../../globaldata'

export default class Index extends Component {

  config = {
    navigationBarTitleText: '首页'
  };

  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      items: [],
      swiperitems: [configs.cdnserver + 'banner1.png', configs.cdnserver + 'banner2.png', configs.cdnserver + 'banner3.png']
    };
  }

  componentWillMount() {
    let self = this;
    setGlobalData('test',999)
    var web_if = Taro.getEnv().toUpperCase() === 'WEB'
    if(web_if){
      ajax({
        method: 'get',
        url: configs.apis['goods'],
        data: {
          'app_id': configs.app_id
        },
        header:{},
        success: function (res) {
          console.log(res)
          self.setState({ items: res.res.items });
        },
        fail: function (response) {
          console.log(response)
        }
      })
    }else {
      var search_data = {
        url: configs.apis['goods'],
        data: { 'app_id': configs.app_id }
      }
      request_good(search_data).then(res => {
        self.setState({ items: res.res.items });
        console.log(res.res.items);
      });
    }
  }

  goProduct(gid, e) {
    console.log(gid)
    Taro.navigateTo({
      url: '/pages/product/product?gid=' + gid ,
    })
  }

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  render() {
    var { items, swiperitems } = this.state;
    var products = <View className="products">
        {items.map(post => <View key={post.sort} className="product" onClick={this.goProduct.bind(this, post.gid)} >
              <Image src={post.thumb} className="product_img" />
              <Text className="product_name">{post.title}</Text>
            </View>)}
      </View>;
    var swiper = <Swiper className="test-h" indicatorColor="#999" indicatorActiveColor="#333" circular indicatorDots autoplay>
        {swiperitems.map((post, index) => <SwiperItem key={index} style={'width:' + window.screen.width}>
            <Image src={post} className="swiper_img" />
          </SwiperItem>)}
      </Swiper>;

    return <View className="index test">
        {swiper}
        <Text>Hello world!</Text>
        <Text>It is {this.state.date.toLocaleTimeString()}.</Text>
        {products}
      </View>;
  }
}
